<template>
  <div class="lang-dropdown bg-gray-x pointer" @click="showLangOptions = !showLangOptions">
    <div class="d-flex align-center justify-space-between">
      <div class="d-flex justify-center align-center">
        <Icon class="me-2" name="language"></Icon>
      </div>
      <div class="d-flex justify-center align-center">
        <span class="font-size-14 font-weight-500 line-height-140">{{ localeText }}</span>
        <Icon class="ms-2 arrow-icon" :class="{ open: showLangOptions }" name="arrowRight"></Icon>
      </div>
    </div>
    <transition name="expand">
      <div v-show="showLangOptions" class="options bg-gray-x">
        <div v-for="l in locales" :key="l.label" class="option" @click="selectLang(l.value)">
          <Icon v-if="locale === l.value" class="me-1 icon-size-12" name="check"></Icon>
          {{ $t(`lang.${l.label}`) }}
        </div>
      </div>
    </transition>
  </div>
</template>

<script setup>
import { computed, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { storeToRefs } from 'pinia'
import { $t, locales, setLocale } from '@/i18n'

const { locale } = storeToRefs(useI18n())
const localeText = computed(() => {
  const v = locale.value
  const key = v.replace('-', '_')
  return $t(`lang.${key}`)
})
const showLangOptions = ref(false)
async function selectLang(langCode) {
  try {
    await setLocale(langCode)
  } catch (e) {
    console.error(e)
  }
}
</script>

<style lang="scss" scoped>
.lang-dropdown {
  height: 2.5rem;
  padding: 0.625rem 1rem;
  border-radius: 3.125rem;
  position: relative;

  .options {
    width: fit-content;
    height: 19.5rem;
    margin-top: 0.5rem;
    border-radius: 0.3125rem;
    box-shadow: 0 0.25rem 0.5rem rgba(0, 0, 0, 0.1);
    color: white;
    position: absolute;
    left: 0;
    top: 2.25rem;
    overflow: auto;
    text-align: end;

    .option {
      padding: 0.25rem 1rem;
      border-bottom: 0.0625rem solid rgb(var(--v-theme-background));
      transition: background-color 0.3s;
      &:last-child {
        border-bottom: none;
      }

      &:hover {
        background-color: rgb(var(--v-theme-primary));
        color: white;
      }
    }
  }

  .arrow-icon {
    transform: rotate(90deg);
    transition: transform 0.1s;
    &.open {
      transform: rotate(270deg);
    }
  }
}
</style>
